package com.cinema.util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Logger {
    private static final String LOG_FILE = "data/logs/system.log";
    private static PrintWriter writer;

    static {
        try {
            // 确保日志目录存在
            java.nio.file.Files.createDirectories(java.nio.file.Paths.get("data/logs"));
            writer = new PrintWriter(new FileWriter(LOG_FILE, true));
        } catch (IOException e) {
            System.err.println("无法初始化日志系统: " + e.getMessage());
        }
    }

    public static void log(String level, String message, String user) {
        String timestamp = LocalDateTime.now().format(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String logEntry = String.format("[%s] %s - %s - %s: %s",
                timestamp, level, user, Thread.currentThread().getName(), message);

        System.out.println(logEntry);
        if (writer != null) {
            writer.println(logEntry);
            writer.flush();
        }
    }

    public static void info(String message, String user) {
        log("INFO", message, user);
    }

    public static void warn(String message, String user) {
        log("WARN", message, user);
    }

    public static void error(String message, String user) {
        log("ERROR", message, user);
    }

    public static void close() {
        if (writer != null) {
            writer.close();
        }
    }
}
